package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.exception.AdminSometingErrorException;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private WorkspaceService workspaceService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 指定时间内的营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {

        if (begin == null || end == null){
            throw new AdminSometingErrorException("日期选择错误");
        }
        //封装日期集合和营业额集合
        StringBuilder dateList = new StringBuilder();
        StringBuilder turnoverList = new StringBuilder();
        for (LocalDate date = begin; !date.isAfter(end); date = date.plusDays(1)){
            dateList.append(date).append(",");
            //获取当天营业额
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            turnoverList.append(reportMapper.sumTurnover(beginTime, endTime) == null ? 0 : reportMapper.sumTurnover(beginTime, endTime)).append(",");
        }
        //删除最后一个多余的逗号
        dateList.deleteCharAt(dateList.length() - 1);
        turnoverList.deleteCharAt(turnoverList.length() - 1);
        log.info("营业额统计:{}\n{}", dateList, turnoverList);
        return new TurnoverReportVO(dateList.toString(), turnoverList.toString());
    }

    /**
     * 指定时间内的用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {

        if(begin == null || end == null){
            throw new AdminSometingErrorException("日期选择错误");
        }
        //封装日期
        StringBuilder dateList = new StringBuilder();
        StringBuilder totalUserList = new StringBuilder();
        StringBuilder newUserList = new StringBuilder();
        Integer totalUser = 0;
        for(LocalDate date = begin; !date.isAfter(end);date = date.plusDays(1)){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer newUser = reportMapper.countUser(beginTime, endTime) == null ? 0 : reportMapper.countUser(beginTime, endTime);
            totalUser += newUser;
            dateList.append(date).append(",");
            totalUserList.append(totalUser).append(",");
            newUserList.append(newUser).append(",");
        }
        log.info("总用户：{}\n新增用户：{}", totalUser, newUserList);
        return new UserReportVO(dateList.toString(), totalUserList.toString(), newUserList.toString());
    }

    /**
     * 指定时间内的订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        if (begin == null || end == null){
            throw new AdminSometingErrorException("日期选择错误");
        }
        //封装日期
        StringBuilder dateList = new StringBuilder();
        StringBuilder orderCountList = new StringBuilder();
        StringBuilder validOrderCountList = new StringBuilder();
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;
        Double orderCompletionRate = 0.0;
        for (LocalDate date = begin; !date.isAfter(end); date = date.plusDays(1)){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer totalOrder = reportMapper.countOrder(beginTime, endTime, null);
            Integer validOrder = reportMapper.countOrder(beginTime, endTime, 5);
            //处理null数据
            totalOrder = totalOrder == null ? 0 : totalOrder;
            validOrder = validOrder == null ? 0 : validOrder;
            //增加总数
            totalOrderCount += totalOrder;
            validOrderCount+= validOrder;
            dateList.append(date).append(",");
            orderCountList.append(totalOrder).append(",");
            validOrderCountList.append(validOrder).append(",");
        }
        orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        return new OrderReportVO(dateList.toString(), orderCountList.toString(), validOrderCountList.toString(), totalOrderCount, validOrderCount, orderCompletionRate);
    }

    /**
     * 查询销量排名前10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //StringBuilder numberList = new StringBuilder();
        //StringBuilder  nameList = new StringBuilder();
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> toplist = reportMapper.getSalesTop10(beginTime, endTime);
//        for (GoodsSalesDTO goodsSalesDTO : toplist){
//            nameList.append(goodsSalesDTO.getName()).append(",");
//            numberList.append(goodsSalesDTO.getNumber()).append(",");
//        }
        //采用stream流的方式实现提取内容
        List<String> names = toplist.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = toplist.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String name = StringUtils.join(names, ",");
        String number = StringUtils.join(numbers, ",");
        return new SalesTop10ReportVO(name, number);
        //return new SalesTop10ReportVO(nameList.toString(), numberList.toString());
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //1. 查询数据库，获取营业数据（过去30天）
        //获得前30天的开始时间
        LocalDateTime begin = LocalDateTime.now().with(LocalTime.MIN).plusDays(-30);
        //获得当天的结束时间
        LocalDateTime end = LocalDateTime.now().with(LocalTime.MAX).plusDays(-1);
        BusinessDataVO businessData = workspaceService.getBusinessData(begin, end);

        //2. 通过POI将数据写入Excel
        try {
            InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/dataReportTemplate.xlsx");
            //基于原有的模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("sheet1");
            XSSFRow row2 = sheet.getRow(1);
            //第二行，第二列：设置日期
            row2.getCell(1).setCellValue("时间：" + begin.toLocalDate().toString() + "——————" + end.toLocalDate().toString());

            XSSFRow row4 = sheet.getRow(3);
            //第四行，第三列：设置营业额
            row4.getCell(2).setCellValue(businessData.getTurnover());
            //第四行，第五列：设置有效订单比率
            row4.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            //第四行，第七列：设置新增用户数
            row4.getCell(6).setCellValue(businessData.getNewUsers());

            XSSFRow row5 = sheet.getRow(4);
            //第五行，第三列：设置有效订单数
            row5.getCell(2).setCellValue(businessData.getValidOrderCount());
            //第五行，第五列：设置平均客单价
            row5.getCell(4).setCellValue(businessData.getUnitPrice());

            int i = 7;
            for (LocalDate date = begin.toLocalDate(); !date.isAfter(end.toLocalDate()); date = date.plusDays(1), i++){
                XSSFRow row = sheet.getRow(i);
                row.getCell(1).setCellValue(date.toString());
                LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
                LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
                BusinessDataVO data = workspaceService.getBusinessData(beginTime, endTime);
                row.getCell(2).setCellValue(data.getTurnover());
                row.getCell(3).setCellValue(data.getValidOrderCount());
                row.getCell(4).setCellValue(data.getOrderCompletionRate());
                row.getCell(5).setCellValue(data.getUnitPrice());
                row.getCell(6).setCellValue(data.getNewUsers());
            }

            //3. 将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源：excel out
            excel.close();
            out.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
